package com.kaiedu.spring.component;

import com.kaiedu.spring.annotation.kaiComponent;
import com.kaiedu.spring.processor.kaiBeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author kai
 * @version 1.0
 * @date 2024/6/13
 * @Description 这是我们自己的后置处理器
 * 实现BeanPostProcessor
 * 重写两个方法
 */
@kaiComponent
public class myBeanPostProcessor implements kaiBeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

        System.out.println("后置处理器kaiBeanPostProcessor  before 被调用  bean类型" + bean.getClass() + "Bean的名字=" + beanName);

        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {

        System.out.println("后置处理器kaiBeanPostProcessor  after 被调用  bean类型" + bean.getClass() + "Bean的名字=" + beanName);
        System.out.println("------------------------");
        if ("smartDog".equals(beanName)) {
//            使用jdk动态代理，返回bean的代理对象
            Object o = Proxy.newProxyInstance(kaiBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("method=" + method.getName());
                            Object result = null;

                            if ("getSum".equals(method.getName())) {
                                SmartAnimalAspect.showbeginLog();

                                result = method.invoke(bean, args);
                                SmartAnimalAspect.showsuccessLog();


                            } else {
                                result = method.invoke(bean, args);
                            }
                            return result;
                        }
                    });


            return o;
        }

        return bean;
    }
}
